package village.rainbow.slipin;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import village.rainbow.slipin.database.dao.NormalDao;
import village.rainbow.slipin.exception.ToFinishException;
import village.rainbow.slipin.ui.ApplicationInfoActivity;
import village.rainbow.slipin.ui.NoticeActivity;
import village.rainbow.slipin.ui.TutorialActivity;
import village.rainbow.slipin.uicontrol.OnSizeChangedCompleteListener;
import village.rainbow.slipin.uicontrol.ResizeLayout;
import village.rainbow.slipin.util.DateUtil;
import village.rainbow.slipin.util.ShortcutUtil;
import village.rainbow.slipin.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

public abstract class BaseActivity extends Activity implements OnClickListener{

	private TextView mTitleView;
	public NormalDao mDao;
	public DataProvider mContentProvider;
	
	private ResizeLayout mResizeLayout;

	private ShortcutUtil mShortcutUtil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_base);
		
		mResizeLayout = (ResizeLayout)findViewById(R.id.layout_base);
		mResizeLayout.setDestScreenSize(720, 1230, true);		// 베이스레이아웃 설정
		
		Global.init(this);
		mDao = new NormalDao(this);
		mContentProvider = new DataProvider();
		mShortcutUtil = new ShortcutUtil(this, mContentProvider);
		
		mResizeLayout.setOnSizeChangedCompleteListener(new OnSizeChangedCompleteListener() {
			@Override
			public void onSizeChangedComplete() {
				OnSizeChangeComplete();
			}
		});
	}
	
	public abstract void OnSizeChangeComplete();

	public ShortcutUtil getShortcutUtil(){
		return mShortcutUtil;
	}

	@Override
	public void setContentView(int layoutResID) {
		LinearLayout content = (LinearLayout)findViewById(R.id.content);
		getLayoutInflater().inflate(layoutResID, content);
		mTitleView = (TextView)findViewById(R.id.menu_title);
		mTitleView.setTypeface(Typeface.MONOSPACE);
	}
	
	public void errorHandler(Exception e) {
		this.errorHandler(e, true);
	}

	public void errorHandler(final Exception x, final boolean showMessage) {
		x.printStackTrace(); 
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				if(!showMessage)
					return;

				String causeMessage = x.getMessage();
				if(x instanceof ToFinishException){
					showDialog(causeMessage, true);
				}else{
					showDialog(causeMessage);	
				}

			}
		});
	}

	protected void showDialog(String causeMessage) {
		this.showDialog(causeMessage, false);
	}

	protected void showDialog(String causeMessage, boolean activityClose) {
		try{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.ic_launcher);
			builder.setTitle("안내");
			builder.setMessage(causeMessage);
			builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		}catch(Exception e){
			e.printStackTrace();

		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id){
		case R.id.btn_close:
			hideTopMenu();
			break;
		case R.id.btn_notice:
			showNoticeActivity();
			break;
		case R.id.btn_tutorial:
			showTutorialActivity();
			break;
		case R.id.btn_app_info:
			showAppInfoActivity();
			break;
		}
	}

	private void showAppInfoActivity() {
		Intent i = new Intent(this, ApplicationInfoActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(i);
	}

	private void showTutorialActivity() {
		Intent i = new Intent(this, TutorialActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(i);
	}

	private void showNoticeActivity() {
		Intent i = new Intent(this, NoticeActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(i);
	}

	public void shareScene(Bitmap bitmap, String sceneTxt) throws Exception {

		Bitmap bmp = writingText(bitmap, sceneTxt);

		long img = System.currentTimeMillis();
		FileOutputStream Os = openFileOutput("Slipin_" + img + ".png", Context.MODE_WORLD_READABLE);
		bmp.compress(Bitmap.CompressFormat.PNG, 100, Os);
		Os.close();
		bmp.recycle();

		File F = getFileStreamPath("Slipin_" + img + ".png");
		Uri U = Uri.fromFile(F);

		String subject = "Slip in";
		String smsbody = sceneTxt;

		Intent i = new Intent(Intent.ACTION_SEND);
		i.addCategory("android.intent.category.DEFAULT");
		i.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		i.putExtra(android.content.Intent.EXTRA_TEXT, smsbody);
		i.setType("image/png");
		i.putExtra(Intent.EXTRA_STREAM, U);
		startActivity(Intent.createChooser(i,"Share"));

		setResult(Activity.RESULT_OK);
		finish();
	}

	private static byte[] streamToBytes(InputStream is) {
		ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
		byte[] buffer = new byte[1024];
		int len;
		try {
			while ((len = is.read(buffer)) >= 0) {
				os.write(buffer, 0, len);
			}
		} catch (java.io.IOException e) {
		}
		return os.toByteArray();
	}

	public void shareSceneGif(String gifPath) throws Exception {

		File file = new File(gifPath);
		FileInputStream fis = new FileInputStream(file);
		byte[] array = streamToBytes(fis);	

		String[] gifPathArr = gifPath.split("/");
		String gifImgFileName = gifPath.split("/")[gifPathArr.length-1];

		//		File F = getFileStreamPath("DailyScene_" + gifImgFileName);
		//		File F = getFileStreamPath(gifImgFileName);
		File F = new File(Environment.getExternalStorageDirectory() + Global.SDCARD_PATH + "/gif", gifImgFileName);
		Uri U = Uri.fromFile(F);

		String subject = "Slip in";
		String smsbody = "Slip";

		//		file:///storage/emulated/0/dailyscene/20140816160857.gif

		Intent i = new Intent(Intent.ACTION_SEND);
		i.addCategory("android.intent.category.DEFAULT");
		i.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		i.putExtra(android.content.Intent.EXTRA_TEXT, smsbody);
		i.setType("image/gif");
		i.putExtra(Intent.EXTRA_STREAM, U);
		startActivity(Intent.createChooser(i,"Share"));

		setResult(Activity.RESULT_OK);
		finish();
	}

	protected Bitmap writingText(Bitmap bmp, String sceneTxt) {
		Bitmap bitmap = null;
		try{
			bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
			bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight());
			Canvas canvas = new Canvas(bitmap);

			Paint paint = new Paint();
			paint.setAlpha(50);
			paint.setAntiAlias(true);
			paint.setStyle(Paint.Style.FILL);

			int rectHeight = bitmap.getHeight()/5;

			canvas.drawRect(new Rect(0, bitmap.getHeight()/5*4, bitmap.getWidth(), bitmap.getHeight()), paint);

			float textSize = 30.0f;

			int textYOffset = (int) ((rectHeight - textSize)/2 + textSize + bitmap.getHeight()/5*4);

			TextPaint tp = new TextPaint();
			tp.setTypeface(Typeface.MONOSPACE);
			tp.setColor(Color.WHITE);
			tp.setAntiAlias(true);
			tp.setTextSize(textSize);

			int textXOffset = (bitmap.getWidth() - (int)tp.measureText(sceneTxt))/2;
			canvas.drawText(sceneTxt, textXOffset, textYOffset, tp);
			canvas.save();
			return bitmap;
		}finally{
			bmp.recycle();
			//			bitmap.recycle();
		}

	}

	public Bitmap drawableToBitmap (Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable)drawable).getBitmap();
		}

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap); 
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}


	private View mTopMenuView;

	private void showTopMenu() {
		if(mTopMenuView != null)
			return;

		RelativeLayout layoutBase = (RelativeLayout)findViewById(R.id.layout_base);
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.control_top_menu, null);
		v.setClickable(true);
		v.setOnClickListener(this);
		layoutBase.addView(v);
		layoutBase.invalidate();

		v.findViewById(R.id.btn_close).setOnClickListener(this);
		v.findViewById(R.id.btn_notice).setOnClickListener(this);
		v.findViewById(R.id.btn_tutorial).setOnClickListener(this);
		v.findViewById(R.id.btn_app_info).setOnClickListener(this);
		mTopMenuView = v;
	}

	private void hideTopMenu() {
		if(mTopMenuView == null)
			return;

		RelativeLayout layoutBase = (RelativeLayout)findViewById(R.id.layout_base);
		layoutBase.removeView(mTopMenuView);
		mTopMenuView = null;
	}

	@Override
	public void onBackPressed() {
		if(mTopMenuView == null)
			super.onBackPressed();
		else{
			hideTopMenu();
		}
	}

	// 알람 등록
	@SuppressLint("SimpleDateFormat")
	protected void setAlarm(Context context, long alarmTime, int requestCode, String title, String message) throws ParseException{  
		Log.i("TEST", "setAlarm()"); 

		Intent intent = new Intent("village.rainbow.slipin.BROADCAST_ALARM");
		intent.putExtra("title", title);
		intent.putExtra("message", message); 
		intent.putExtra("noti_id", requestCode);

		PendingIntent mAlarmSender;
		mAlarmSender = PendingIntent.getBroadcast(this, (int)requestCode, intent, 0);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date dateAlarm = sdf.parse((alarmTime + ""));
		Date currentTm = sdf.parse(StringUtil.currentDate("yyyyMMddHHmmss"));

		long differ = dateAlarm.getTime() - currentTm.getTime(); //(int) (alarmTime - Long.parseLong(StringUtil.currentDate("yyyyMMddHHmmss"))); 
		//differ *= 1000;
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + differ, mAlarmSender);

	}

	// 알람 해제
	protected void releaseAlarm(Context context, int requestCode){  
		Log.i("TEST", "releaseAlarm()"); 
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

		Intent Intent = new Intent(Global.INTENT_ACTION);
		PendingIntent pIntent = PendingIntent.getBroadcast(context, requestCode, Intent, 0);
		alarmManager.cancel(pIntent);

		// 주석을 풀면 먼저 실행되는 알람이 있을 경우, 제거하고
		// 새로 알람을 실행하게 된다. 상황에 따라 유용하게 사용 할 수 있다.
		//		alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, pIntent);
	}


	public void showDateTimePicker(final Button btnDate) {
		int year = Integer.parseInt(StringUtil.CurrentYear());
		int month = Integer.parseInt(StringUtil.CurrentMonth()) - 1;
		int date = Integer.parseInt(StringUtil.CurrentDay());

		// 날짜 먼저 선택함
		DatePickerDialog datePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				String selectedDate = year + StringUtil.addZero((monthOfYear+1)) + StringUtil.addZero(dayOfMonth);
				showTimePicker(selectedDate, btnDate);
			}
		}, year, month, date);
		datePickerDialog.setTitle("알람 날짜 선택");
		datePickerDialog.show();
	}

	public void showTimePicker(final String selectedDate, final Button btnDate) {

		int hourOfDay = Integer.parseInt(StringUtil.currentDate("HH"));
		int minute = Integer.parseInt(StringUtil.currentDate("mm"));

		TimePickerDialog timePickerDialog = new TimePickerDialog(this, new OnTimeSetListener() {
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				try{
					String alarmTime = selectedDate + StringUtil.addZero(hourOfDay) + StringUtil.addZero(minute) + StringUtil.addZero(0);
					btnDate.setTag(alarmTime);
					alarmTime = DateUtil.toPatternedDate("yyyy.MM.dd HH:mm", "yyyyMMddHHmmss", alarmTime);
					btnDate.setText(alarmTime);	

				}catch(Exception e){
					errorHandler(e);
				}
			}
		}, hourOfDay, minute, true);
		timePickerDialog.show();
	}
	
	public ResizeLayout getResizeLayout(){
		return mResizeLayout;
	}

	public float getParentRatioW(){
		return mResizeLayout.getChildRatioW();
	}
	
	public float getParentRatioH(){
		return mResizeLayout.getChildRatioH();
	}
	
	
}
